package com.cn.wanxi.servlet.back.user;

import com.cn.wanxi.dto.UserDto;
import com.cn.wanxi.model.UserModel;
import com.cn.wanxi.service.IUserService;
import com.cn.wanxi.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/UserLoginServlet")
public class UserLoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //        1.乱码解决
//        2.获取用户传递过来的值
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        String sessionCode = (String) req.getSession().getAttribute("code");

//        3.将这些值封装到我们的model
        UserDto userDto = new UserDto();
        userDto.setUserModel(new UserModel());
        userDto.getUserModel().setUsername(username);
        userDto.getUserModel().setPassword(password);
        userDto.setCode(code);
        userDto.setSessionCode(sessionCode);
//        4.新建service服务逻辑层，调用
        IUserService iUserService = new UserServiceImpl();
        String result = iUserService.Login(userDto);
        req.setAttribute("result", result);
        if (result.equals("成功登陆")) {
            req.getSession().setAttribute("username", username);
            req.getRequestDispatcher("/back/homeManage.jsp").forward(req, resp);
        } else {
            //        5.返回数据并转发到页面
            req.getRequestDispatcher("/back/userLogin.jsp").forward(req, resp);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
